import Taro from '@tarojs/taro'

var _this = this

const formatTime = date => {
  if(!date) return ''
  date = new Date(date)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return (
    [year, month, day].map(formatNumber).join('-')
  )
}
const format = function(date, fmt) {
  //author: meizz
  var o = {
    'M+': date.getMonth() + 1, //月份
    'd+': date.getDate(), //日
    'h+': date.getHours(), //小时
    'm+': date.getMinutes(), //分
    's+': date.getSeconds(), //秒
    'q+': Math.floor((date.getMonth() + 3) / 3), //季度
    S: date.getMilliseconds() //毫秒
  }
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  for (var k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      )
  return fmt
}
const app = Taro.getApp()
const rpc = (service, params = {}, config = {}) => {
  const dataMap = config.dataMap || (res => res.data)

  return new Promise((resolve, reject) => {
    Taro.request({
      url: service.url,
      method: service.method || 'get',
      data: params,
      header: {
        Authorization: 'token ' + app.globalData.token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: res => {
        if (res.statusCode === 200 && res.data.success) {
          resolve(dataMap(res.data))
        }
      },
      fail: reject
    })
  })
}

const fromNowOn = function(dest) {
  const date = new Date(dest).getTime()
  const now = new Date().getTime()

  if (now - date < 3600000) {
    let str = '刚刚'
    const temp = Math.floor((now - date) / 60000)
    if (temp) {
      str = `${temp}分钟前`
    }
    return str
  } else if (now - date < 86400000) {
    // 小于1天
    return `${Math.floor((now - date) / 3600000)}小时前`
  } else if (now - date < 2592000000) {
    return `${Math.floor((now - date) / 86400000)}天前`
  } else {
    return formatTime(dest, 'MM-dd')
  }
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const transSuccToPro = func => {
  return new Promise((re, rj) => {
    func({
      success: re,
      fail: rj
    })
  })
}

const getUserInfo = app => {
  return new Promise((resolve, reject) => {
    if (app.globalData.userInfo) {
      resolve({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (_this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        resolve({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      Taro.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          resolve({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  })
}

const onShow = type => {
  console.log({ wx })
  // wx.setNavigationStyle('custom')
}

module.exports = {
  formatTime,
  format,
  transSuccToPro,
  rpc,
  app,
  fromNowOn,
  getUserInfo,
  onShow
}
